import 'dart:async';
import 'package:flutter_pink_app/business/token.dart';
import 'package:flutter_pink_app/net/base/error.dart';
import 'package:flutter_pink_app/net/base/response.dart';
import '../net/index.dart';
import '../net/request/login_request.dart';
import '../net/adater/dio_adapter.dart';

// 业务登录函数
Future<BaseResponse<String>> loginAccount(
    String username, String password) async {
  final headerField = {
    'userName': username,
    'password': password,
  }; // 头信息对应字段
  final request = LoginRequest();
  // 设置头信息
  headerField.forEach((key, value) => request.setQueryParams(value, key));
  final network = NetworkCall.getInstance(adapter: DioAdapter());
  BaseResponse<String> res;
  try {
    res = await network.send<String>(request); // 拿到请求结果
  } on BaseNetworkError catch (e) {
    e.expectedErrorLog();
    res = BaseResponse(
        data: e.toString(), statusCode: e.statusCode, message: e.message);
  }
  _handleLoginRes(res); // 处理登陆请求结果
  return res;
}

// 处理登陆请求结果
void _handleLoginRes(BaseResponse<String> res) {
  // 状态码不等于0则不处理
  if (res.statusCode != 0) {
    return;
  }
  // 不为空则取出token并存储
  if (res.data.toString() != 'null') {
    final tokenValue = res.data;
    setToken(tokenValue);
  }
}
